package com.csap.framework.oauth2.server.login.spi;

import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import com.csap.framework.oauth2.request.MobileRequest;
import com.csap.framework.oauth2.request.RegisterRequest;
import com.csap.framework.oauth2.server.login.Oauth2LoginSpi;
import com.csap.framework.oauth2.server.service.Oauth2ServerService;
import com.csap.framework.util.bean.BeanCopierUtil;
import com.csap.framework.util.optional.Optional;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 根据手机号登陆
 *
 * @Author ycf
 * @Date 2021/8/9 4:48 下午
 * @Version 1.0
 */
@Component
public class Oauth2LoginSpiMobile implements Oauth2LoginSpi<MobileRequest, AccessTokenModel> {
    @Resource
    private Oauth2ServerService oauth2ServerService;

    @Override
    public AccessTokenModel login(MobileRequest otherOpenIdRequest) {
        return Optional.of(otherOpenIdRequest)
                .then(i -> SaOAuth2Util.checkClientModel(otherOpenIdRequest.getClientId()))
                .map(i -> BeanCopierUtil.copy(otherOpenIdRequest, RegisterRequest.class).setUserName(otherOpenIdRequest.getMobile()))
                .when(i -> oauth2ServerService.isRegister(i, false), oauth2ServerService::register)
                .map(i -> oauth2ServerService.loginMobile(otherOpenIdRequest.getMobile(), otherOpenIdRequest.getPlatform(), otherOpenIdRequest.getClientId(), otherOpenIdRequest.getDeviceType(), ""))
                .get();
    }
}
